<template>
  <div class="transport-request">
    <van-nav-bar
        title="运送申请"
        left-arrow
        @click-left="onClickLeft"
    />

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
            v-model="formData.shippingtype"
            is-link
            readonly
            name="workType"
            label="工单类别"
            placeholder="请选择工单类别"
            @click="showWorkTypePicker = true"
        />
        <van-popup v-model:show="showWorkTypePicker" position="bottom">
          <van-picker
              :columns="workTypeColumns"
              @confirm="onWorkTypeConfirm"
              @cancel="showWorkTypePicker = false"
              :show-toolbar="true"
              toolbar-position="top"
              :columns-top="0"
          />
        </van-popup>

        <van-field
            v-model="formData.shippingpriority"
            is-link
            readonly
            name="priority"
            label="优先级"
            placeholder="请选择优先级"
            @click="showPriorityPicker = true"
        />
        <van-popup v-model:show="showPriorityPicker" position="bottom">
          <van-picker
              :columns="priorityColumns"
              @confirm="onPriorityConfirm"
              @cancel="showPriorityPicker = false"
              :show-toolbar="true"
              toolbar-position="top"
              :columns-top="0"
          />
        </van-popup>

        <van-field
            v-model="formData.shippingstarttime"
            is-link
            readonly
            name="startTime"
            label="开始时间"
            placeholder="请选择开始时间"
            @click="showTimePicker = true"
        />
        <van-popup v-model:show="showTimePicker" position="bottom">
          <van-datetime-picker
              type="datetime"
              @confirm="onTimeConfirm"
              @cancel="showTimePicker = false"
              :show-toolbar="true"
              toolbar-position="top"
              :columns-top="0"
          />
        </van-popup>

        <van-field
            v-model="formData.shippinglimit"
            type="digit"
            name="duration"
            label="处理时限(小时)"
            placeholder="请输入处理时限"
        />

        <van-field
            v-model="formData.shippingstarting"
            is-link
            readonly
            name="startLocation"
            label="起始科室"
            placeholder="请选择起始科室"
            @click="showStartLocationPicker = true"
        />
        <van-popup v-model:show="showStartLocationPicker" position="bottom">
          <van-picker
              :columns="locationColumns"
              @confirm="onStartLocationConfirm"
              @cancel="showStartLocationPicker = false"
              :show-toolbar="true"
              toolbar-position="top"
              :columns-top="0"
          />
        </van-popup>

        <van-field
            v-model="formData.shippinggoal"
            is-link
            readonly
            name="endLocation"
            label="目标科室"
            placeholder="请选择目标科室"
            @click="showEndLocationPicker = true"
        />
        <van-popup v-model:show="showEndLocationPicker" position="bottom">
          <van-picker
              :columns="locationColumns"
              @confirm="onEndLocationConfirm"
              @cancel="showEndLocationPicker = false"
              :show-toolbar="true"
              toolbar-position="top"
              :columns-top="0"
          />
        </van-popup>

        <van-field
            v-model="formData.shippingscene"
            is-link
            readonly
            name="shippingScene"
            label="运送场景"
            placeholder="请选择运送场景"
            @click="shippingScene = true"
        />
        <van-popup v-model:show="shippingScene" position="bottom">
          <van-picker
              :columns="shippingScenes"
              @confirm="onSceneConfirm"
              @cancel="shippingScene = false"
              :show-toolbar="true"
              toolbar-position="top"
              :columns-top="0"
          />
        </van-popup>
        <van-field
            v-model="formData.shippingtool"
            is-link
            readonly
            name="transportTool"
            label="运送工具"
            placeholder="请选择运送工具"
            @click="showToolPicker = true"
        />
        <van-popup v-model:show="showToolPicker" position="bottom">
          <van-picker
              :columns="toolColumns"
              @confirm="onToolConfirm"
              @cancel="showToolPicker = false"
              :show-toolbar="true"
              toolbar-position="top"
              :columns-top="0"
          />
        </van-popup>
        <van-field
            v-model="formData.shippingnumber"
            type="digit"
            name="staffCount"
            label="运送人员人数"
            placeholder="请输入人数"
        />

        <van-field
            v-model="formData.shippingdescribe"
            type="textarea"
            name="description"
            label="任务描述"
            placeholder="请输入任务描述"
            rows="3"
            autosize
        />

        <van-field
            v-model="formData.shippingreportname"
            name="contact"
            label="上报人"
            placeholder="请输入"
        />
        <van-field
            v-model="formData.shippingphone"
            name="contact"
            label="联系电话"
            placeholder="请输入联系电话"
        />

        <van-field
            v-model="formData.shippingremarks"
            type="textarea"
            name="remarks"
            label="备注"
            placeholder="请输入备注信息"
            rows="2"
            autosize
        />

        <van-field
            name="uploader"
            label="附件"
        >
          <template #input>
            <van-uploader
                v-model="fileList"
                :max-count="3"
                :before-read="beforeRead"
                :after-read="afterRead"
                multiple
            />
          </template>
        </van-field>
      </van-cell-group>

      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit" @submit="findAdd">
          提交任务
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from 'vant';

export default {
  name: 'TransportRequestView',
  data() {
    return {
      showWorkTypePicker: false,
      showPriorityPicker: false,
      showTimePicker: false,
      showStartLocationPicker: false,
      showEndLocationPicker: false,
      showToolPicker: false,
      shippingScene: false,
      workTypeColumns: [
        { text: '预约运送工单', value: '1' },
        { text: '临时运送工单', value: '2' }
      ],
      priorityColumns: [
        { text: '普通', value: '1' },
        { text: '紧急', value: '2' },
        { text: '特急', value: '3' }
      ],
      locationColumns: [
        { text: '门诊部', value: '1' },
        { text: '急诊科', value: '2' },
        { text: '内科', value: '3' },
        { text: '外科', value: '4' },
        { text: '手术室', value: '5' },
        { text: '检验科', value: '6' },
        { text: '放射科', value: '7' }
      ],
      toolColumns: [
        { text: '平车', value: '1' },
        { text: '轮椅', value: '2' },
        { text: '担架', value: '3' },
        { text: '其他', value: '4' }
      ],
      shippingScenes: [
        {text: '医疗室', value: '1'},
        {text: '太平间', value: '2'},
        {text: '手术室', value: '3'}
      ],
      formData: {},
      fileList: [],
    }
  },
  created() {
    this.hx();
  },
  methods: {

    hx() {
      const item = localStorage.getItem('aa');

      const aaaa = JSON.parse(item)
      let name = aaaa['username'];
      let phone = aaaa['phone'];

      this.formData.shippingreportname = name;
      this.formData.shippingphone = phone;
    },

    // 提交工单
    findAdd() {
      if (this.fileList.some(file => file.status === 'uploading')) {
        Toast('请等待文件上传完成');
        return;
      }

      this.axios.post("http://localhost:9999/api-central-service/shipping/add", this.formData).then(res => {
        // 判断是否提交成功
        if (res.data.code === 1) {
          Toast.success('提交成功');
          this.$router.back();
        } else {
          Toast.fail('提交失败');
        }
      })
    },

    onClickLeft() {
      this.$router.back()
    },

    onWorkTypeConfirm(value) {
      this.formData.shippingtype = value.text;
      this.showWorkTypePicker = false;
    },

    onPriorityConfirm(value) {
      this.formData.shippingpriority = value.text;
      this.showPriorityPicker = false;
    },

    onTimeConfirm(value) {
      const date = new Date(value);
      this.formData.shippingstarttime = date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-');
      this.showTimePicker = false;
    },

    onStartLocationConfirm(value) {
      this.formData.shippingstarting = value.text;
      this.showStartLocationPicker = false;
    },

    onEndLocationConfirm(value) {
      this.formData.shippinggoal = value.text;
      this.showEndLocationPicker = false;
    },
    onSceneConfirm(value) {
      this.formData.shippingscene = value.text;
      this.shippingScene = false;
    },
    onToolConfirm(value) {
      this.formData.shippingtool = value.text;
      this.showToolPicker = false;
    },

    onSubmit() {
      this.findAdd();
    },

    // 上传前的校验
    beforeRead(file) {
      // 限制文件大小（这里限制为 10MB）
      const maxSize = 10 * 1024 * 1024;
      if (file.size > maxSize) {
        Toast('文件大小不能超过 10MB');
        return false;
      }
      return true;
    },

    // 上传后的处理
    afterRead(file) {
      // 如果是多文件上传，file 是一个数组
      const files = Array.isArray(file) ? file : [file];
      files.forEach((item) => {
        // 创建 FormData
        const formData = new FormData();
        formData.append('file', item.file);

        // 上传文件到服务器
        this.axios.post('http://localhost:9999/api-central-service/oss/upload', formData, {
          headers: {
            // 设置请求头
            'Content-Type': 'multipart/form-data',
          },
        }).then(res => {
          if (res.data) {
            // 初始化 shippingannex 为字符串
            if (!this.formData.shippingannex) {
              this.formData.shippingannex = '';
            }
            // 将文件 URL 添加到字符串中，用逗号分隔
            this.formData.shippingannex = this.formData.shippingannex
                ? this.formData.shippingannex + ',' + res.data
                : res.data;
            Toast.success('文件上传成功');
          } else {
            Toast.fail('文件上传失败');
            const index = this.fileList.indexOf(item);
            if (index !== -1) {
              this.fileList.splice(index, 1);
            }
          }
        }).catch(() => {
          Toast.fail('文件上传失败');
          const index = this.fileList.indexOf(item);
          if (index !== -1) {
            this.fileList.splice(index, 1);
          }
        });
      });
    },
  }
}
</script>

<style scoped>
.transport-request {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 20px;
}

:deep(.van-uploader) {
  padding: 10px 0;
}
</style>